package com.fingard.dsp.bank.directbank.dbs01;

import net.sf.json.JSONObject;

import java.sql.Connection;
import java.util.Date;
import java.util.Map;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.bankInterface.IAcceptNotice;
import com.fingard.generalobj.NoticeReq;
import com.fingard.generalobj.NoticeResp;
import com.fingard.net.listener.SocketReceiver;
import com.fingard.text.StringHelper;

public class DBS01AcceptNotice extends DBS01Base implements IAcceptNotice{

    private static final String UPDATE="UPDATE REQSEQIDMAPPING SET TRANSDATE=?,STATE=?,RESERVE1=? WHERE REQSEQID=?";
    private static final String SELECTSEQ = "SELECT STATE,RESERVE1 FROM REQSEQIDMAPPING WHERE REQSEQID=?;";

    /**
     * 主动接收星展银行推送的ack2，ack3付款状态信息
     * @param p_req
     * @return
     * @throws Exception
     */
    @Override
    public NoticeResp dealNotice(NoticeReq pNtReq) throws Exception {
    	NoticeResp resp = new NoticeResp();
    	String p_req = pNtReq.getReqString();
    	WriteBankLogLn("银行通知返回原始数据:\r\n" + pNtReq.getFullString());
        String string="-----BEGIN PGP MESSAGE-----";//截取响应报文分隔字符
        String endString="-----END PGP MESSAGE-----";//结束分隔符
        Connection conn= FGBiz.getLocalDbConn();
        try {
            if (StringHelper.hasAnyChar(p_req) && p_req.indexOf(string) >= 0 && p_req.indexOf(endString) >=0) {
                String eachJson = p_req.substring(p_req.indexOf(string),p_req.indexOf(endString)+endString.length());
                //GPG数据解密
                String req_String = pgpDecryptAndVerify(eachJson);
                WriteBankLogLn("GPG数据解密后银行响应的报文：" + req_String);
                //返回报文处理
                JSONObject jsonArray = JSONObject.fromObject(req_String.replaceAll(" ", "")
                        .replaceAll("\\[","").replaceAll("]",""));
                if (!"".equals(jsonArray.get("txnResponses")) && jsonArray.get("txnResponses") != null) {
                    JSONObject headObject = (JSONObject) jsonArray.get("header");
                    JSONObject object = (JSONObject) jsonArray.get("txnResponses");
                    String msgId = headObject.get("msgId").toString();//流水号
                    String transState = object.get("responseType").toString() + "+" + object.get("txnStatus").toString();//状态码
                    String txnStatusDescription = object.get("txnStatusDescription").toString();//响应结果
                    //查询返回的付款状态
                    Map<String, Object> selMap=JDBCHelper.execQuerySingle(conn,SELECTSEQ,new Object[]{msgId});
                    if(selMap.size()>0){//存在，更新支付状态
                        //更新付款状态
                        JDBCHelper.update(conn, UPDATE, new Object[]{Format.Date8Format.format(new Date()),transState,txnStatusDescription,msgId});
                        WriteBankLogLn("支付流水号"+msgId+"成功更新状态为"+transState);
                    }else {
                        WriteBankLogLn("支付流水号"+msgId+"未记录，请联系管理员检查");
                    }
                }
            }
        }catch (Exception e){
            WriteBankLogLn("接收服务端主动响应请求异常:", e);
        }finally {
            conn.close();
        }
        String tmpStrRet = "";
        WriteBankLogLn("响应："+tmpStrRet);
        resp.respBytes = tmpStrRet.getBytes(pNtReq.reqCharset);
    	return resp;
    }

    @Override
    public void getContentLength(SocketReceiver p_receiver) throws Exception {

    }
}
